//
//  CZComposeViewController.swift
//  GZWeibo05
//
//  Created by zhangping on 15/11/3.
//  Copyright © 2015年 zhangping. All rights reserved.
//

import UIKit
import SVProgressHUD

enum CZComposeViewControllerType: Int {
    case Compose = 1
    case Repost = 2
    case Comment = 3
}

class CZComposeViewController: UIViewController {
    
    // MARK: - 属性
    /// 微博模型
    var status: CZStatus?
    
    /// 控制器类型
    private var controllerType: CZComposeViewControllerType
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init(controllerType: CZComposeViewControllerType) {
        self.controllerType = controllerType
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 需要设置背景颜色,不然弹出时动画有问题
        view.backgroundColor = UIColor.whiteColor()
        
        prepareUI()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 准备UI
    private func prepareUI() {
        setupNavigationBar()
        setupTextView()
    }
    
    /// 设置导航栏
    private func setupNavigationBar() {
        // 设置按钮, 左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        // 右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
//        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitleView()
    }
 
    /// 设置导航栏标题
    private func setupTitleView() {
        
        // 默认发微博
        var prefix = "发微博"
        if controllerType == CZComposeViewControllerType.Repost {
            prefix = "转发微博"
        } else if controllerType == CZComposeViewControllerType.Comment {
            prefix = "评论微博"
        }
        
        // 获取用户的名称
        if let name = CZUserAccount.loadUserAccount()?.screen_name {
            // 有用户名
            let titleName = prefix + "\n" + name
            
            // 创建可变的属性文本
            let attrString = NSMutableAttributedString(string: titleName)
            
            // 创建label
            let label = UILabel()
            
            // 设置属性文本
            label.numberOfLines = 0
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(14)
            
            // 获取NSRange
            let nameRange = (titleName as NSString).rangeOfString(name)
            
            // 设置属性文本的属性
            attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: nameRange)
            attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
            
            // 顺序不要搞错
            label.attributedText = attrString
            label.sizeToFit()
            
            navigationItem.titleView = label
        } else {
            // 没有用户名
            navigationItem.title = prefix
        }
    }
    
    /// 设置textView
    private func setupTextView() {
        // 添加子控件
        view.addSubview(textView)
        
        // 添加约束
        textView.ff_Fill(view)
    }
    
    /// 关闭控制器
    func close() {
        // 关闭键盘
        textView.resignFirstResponder()
        
        // 关闭sv提示
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发微博
    func sendStatus() {
        // 获取textView的文本内容发送给服务器
        let text = textView.text
        
        if text == nil || text == "" {
            SVProgressHUD.showInfoWithStatus("内容不能为空")
            return
        }
        
        if controllerType == CZComposeViewControllerType.Compose {
            // 显示正在发送
            SVProgressHUD.showWithStatus("正在发布微博...", maskType: SVProgressHUDMaskType.Black)
            
            // 发送微博
            CZNetworkTool.sharedInstance.sendStatus(text) { (result, error) -> () in
                if error != nil {
                    print("error:\(error)")
                    SVProgressHUD.showErrorWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Black)
                    return
                }
                
                print("发布微博成功:\(result)")
                
                // 发送成功, 直接关闭界面
                self.close()
            }
        } else if controllerType == CZComposeViewControllerType.Repost {
            // 显示正在发送
            SVProgressHUD.showWithStatus("正在转发微博...", maskType: SVProgressHUDMaskType.Black)
            
            CZNetworkTool.sharedInstance.repostStatus(status!.id, status: text, finished: { (result, error) -> () in
                if error != nil {
                    print("error:\(error)")
                    SVProgressHUD.showErrorWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Black)
                    return
                }
                
                // 发送成功, 直接关闭界面
                print("转发微博成功:\(result)")
                self.close()
            })
        } else if controllerType == CZComposeViewControllerType.Comment {
            // 显示正在发送
            SVProgressHUD.showWithStatus("正在评论微博...", maskType: SVProgressHUDMaskType.Black)
            
            CZNetworkTool.sharedInstance.commentStatus(status!.id, comment: text, finished: { (result, error) -> () in
                if error != nil {
                    print("error:\(error)")
                    SVProgressHUD.showErrorWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Black)
                    return
                }
                
                // 发送成功, 直接关闭界面
                print("评论微博成功:\(result)")
                self.close()
            })
        }
    }
    
    /// textView
    private lazy var textView: UITextView = {
        let textView = UITextView()
        
        // 当textView被拖动的时候就会将键盘退回,textView能拖动
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.font = UIFont.systemFontOfSize(18)
        textView.backgroundColor = UIColor(white: 0.85, alpha: 1)
        textView.textColor = UIColor.blackColor()
        textView.bounces = true
        textView.alwaysBounceVertical = true
        
        return textView
    }()
}

